#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/1/24 14:18
# @Author  : Seven
# @File    : GaussImage.py
# @Software: PyCharm
# function : 基于背景提取的运动估计

import cv2

# 加载视频
cap = cv2.VideoCapture()
cap.open('768x576.avi')
if not cap.isOpened():
    print("无法打开视频文件")

# 创建一个背景对象
pBgModel = cv2.createBackgroundSubtractorMOG2()


def labelTargets(img, mask, threshold):
    seg = mask.copy()
    # 图像分割
    cnts = cv2.findContours(seg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    count = 0
    for i in cnts[1]:
        area = cv2.contourArea(i)  # 计算面积
        if area < threshold:  # 滤除噪声
            continue
        count += 1  # 统计运动目标数量
        rect = cv2.boundingRect(i)  # 获取运动目标的坐标及长宽
        print("矩形：X:{} Y:{} 宽：{} 高：{}".format(rect[0], rect[1], rect[2], rect[3]))
        cv2.drawContours(img, [i], -1, (255, 255, 0), 1)  # 画出运动目标的轮廓
        cv2.rectangle(img, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 0, 255), 1)  # 画矩形
        cv2.putText(img, str(count), (rect[0], rect[1]), cv2.FONT_HERSHEY_PLAIN, 0.5, (0, 255, 0))  # 给矩形标号
    return count


while True:
    flag, source = cap.read()
    if not flag:
        break
    # 缩小图像尺寸
    image = cv2.pyrDown(source)
    # 检测出前景
    fgMask = pBgModel.apply(image)
    # 形态学滤波
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    morphImage_open = cv2.morphologyEx(fgMask, cv2.MORPH_OPEN, kernel, iterations=5)
    mask = fgMask - morphImage_open
    _, Mask = cv2.threshold(mask, 30, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    # Mask = cv2.GaussianBlur(Mask, (5, 5), 0)
    # 运动目标检测
    targets = labelTargets(image, Mask, 30)

    print("共检测%s个目标" % targets)
    backGround = pBgModel.getBackgroundImage()
    cv2.imshow('source', image)
    cv2.imshow('background', backGround)
    cv2.imshow('foreground', Mask)
    key = cv2.waitKey(100)
    if key == 27:
        break